import { Button, Form, Highlight, Input, Toast, Tooltip } from '@douyinfe/semi-ui'
import React, { useEffect, useState } from 'react'
// @ts-ignore
import { ipcApiRoute } from '@/api/main';
// @ts-ignore
import { ipc } from '@/utils/ipcRenderer';
import { IconHelpCircle } from '@douyinfe/semi-icons';
import { useDebounce, useThrottle } from '../../Hook/useDebounce';

const PythonType = (props: {
  isRunning: any
  setIsRunning: any
}) => {
  const { setIsRunning } = props
  // 定义状态变量
  const [promptPath, setPromptPath] = useState('12121')
  const [isDataLoaded, setIsDataLoaded] = useState(false)
  const [initFields, setInitFields] = useState({}) //Form初始值
  // 处理表单提交

  const handleOnSumit = (values: { coordinates1: string, coordinates2: string, interval: string }) => {
    // 如果promptPath不是 E:\workList\mkdir 这种格式则提示错误
    const pathRegex = /^[A-Z]:\\(?:[^\\\/:*?"<>|\r\n]+\\)*[^\\\/:*?"<>|\r\n]*$/;

    // 使用正则表达式测试提供的路径
    if (!pathRegex.test(promptPath)) {
      return Toast.error('路径错误')
    }
    const pythonOpions = {
      promptPath: promptPath,
      coordinates1: values.coordinates1,
      coordinates2: values.coordinates2,
      interval: values.interval,
    }
    updateDb('update', pythonOpions, 'python')
  }


  // 执行数据库操作
  const updateDb = (ac: string, opions: { promptPath: string; coordinates1: string; coordinates2: string; interval: string; }, type: string) => {
    const params = {
      action: ac,
      type,
      updateInfo: {
        ...opions,
      },
    }
    ipc.invoke(ipcApiRoute.jsondbOperation, params).then((res: any) => {
      if (res.result) {
        Toast.success('保存成功')
        setInitFields({
          coordinates1: res.result.coordinates1,
          coordinates2: res.result.coordinates2,
          interval: res.result.interval,
          promptPath: res.result.promptPath,
        })
      } else {
        Toast.error('操作失败')
      }
    })
  }

  const initJson = () => {

    const params = {
      action: 'add',
      addinfo: {
        "type": "python",
        "promptPath": "C:\\",
        "coordinates1": "851,976",
        "coordinates2": "891,899",
        "interval": 5
      },
    }
    ipc.invoke(ipcApiRoute.jsondbOperation, params).then((res: any) => {
      if (res.result) {
        console.log(res,'resresresresres');
        setPromptPath(res.result[0].promptPath)
        setIsDataLoaded(true)
        setInitFields({
          coordinates1: res.result.coordinates1,
          coordinates2: res.result.coordinates2,
          interval: res.result.interval,
          promptPath: res.result.promptPath,
        })
      } else {
        Toast.error('数据初始化失败')
      }

    })

  }
  const debouncedIpcInvoke = useDebounce(initJson, 1000);
  // 使用useEffect钩子函数获取表单初始值
  useEffect(() => {
    // 获取表单初始值
    ipc.invoke(ipcApiRoute.jsondbOperation, {
      action: 'get', type: "python"
    }).then((res: { result: string | any[]; }) => {
      if (res.result && res.result.length > 0) {
        setPromptPath(res.result[0].promptPath)
        setInitFields(res.result[0])
      } else {
        debouncedIpcInvoke()
      }
      setIsDataLoaded(true)
    })
  }, [])

  // 渲染函数
  return (
    isDataLoaded ? (
      <Form
        style={{ padding: 10, width: '100%', boxSizing: 'border-box' }}
        layout="horizontal"
        onValueChange={(values) => console.log(values)}
        onSubmit={handleOnSumit}
        initValues={initFields}
      >
        <Form.Section text={'步骤1-设置提示词文件'}>
          <Input disabled value={promptPath}></Input>
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
            }}>
            <Button
              style={{
                margin: '10px 0',
              }}
              onClick={() => {
                  ipc.invoke(ipcApiRoute.selectFile, {
                    type:['xls','xlsx']
                }).then((res: React.SetStateAction<string>) => {
                  setPromptPath(res)
                })
              }}
            >
              选择文件
            </Button>

            <span

              style={{
                fontSize: 12,
                marginLeft: '5px',
              }}>
                请将提示词放入<a>Excel</a>表格内-格式请参考
                <a onClick={() => {
                ipc.invoke(ipcApiRoute.openLink, 'https://docs.qq.com/sheet/DUE5hZnBPbnNTd0dH?tab=BB08J2').then((res: any) => {
                  console.log(res, 'res')
                })
              }} >案例文件</a>
            </span>
          </div>
        </Form.Section>
        <Form.Section text={'步骤2-获取坐标'}>
          <div style={{
            display: 'flex', width: '100%', justifyContent: 'start',
          }}>
            <Form.Input
              field="coordinates1"
              label="坐标1"
              trigger={'change'}
              placeholder="例如：200,300"
              rules={[{
                required: true, message: '请输入x,y坐标',
                validator: (_rule, value) => {
                  return /^[0-9]+,[0-9]+$/.test(value)
                }
              }]}

            />
            <Form.Input
              field="coordinates2"
              label="坐标2"
              trigger={'change'}
              placeholder="例如：200,300"
              rules={[{
                required: true, message: '请输入x,y坐标',
                validator: (_rule, value) => {
                  return /^[0-9]+,[0-9]+$/.test(value)
                }
              }]}

            />
            {/* <Form.Input
            field="coordinates3"
            label="坐标3"
            trigger={'blur'}
            placeholder="例如：200,300"
            rules={[{ required: true, message: '此项为必填项' }]}

          /> */}
          </div>
        </Form.Section>
        <Form.Section text={'步骤3-延迟设置'}>
          <div style={{ display: 'flex' }}>
            <Form.InputNumber
              field="interval"
              label={{
                text: '执行间隔（秒）',
                extra: <Tooltip content='每个几秒发送一次提示词'><IconHelpCircle style={{ color: 'var(--semi-color-text-2)' }} /></Tooltip>
              }}
              rules={[{ required: true, message: '请输入执行间隔' }]}

            />
          </div>
        </Form.Section>

        <div
          style={{
            width: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            marginTop: 20,
          }}
        >
          <Button type="primary" htmlType="submit" className="btn-margin-right">
            保存配置
          </Button>
          <Button type='warning' onClick={() => {
            setIsRunning({
              isRunning: true,
              type: 'python',
            })
            ipc.invoke(ipcApiRoute.pythonOperation, {
              fileName: '/Midjunery/Mid-draw/dist/update.exe', type: "start", params: initFields
            }).then((result: any) => {
              if (result.result) {
                setIsRunning({
                  isRunning: true,
                  type: 'python',
                })
                Toast.success(result.message)
              } else {
                Toast.error(result.message)
              }
            })
          }}>
            开始运行
          </Button>
        </div>
      </Form>
    ) : (
      <div>Loading...</div> // 可以显示加载提示
    )

  )
}

export default PythonType